package com.ccnu.JobHub.service.impl;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class EmailService {
    private final JavaMailSender javaMailSender;

    @Value("${global.submitter}")
    private String submitter;
    @Value("${spring.mail.username}")
    private String email;

    /**
     * 构造函数
     * @param javaMailSender 一个对象来发送信息的
     */
    @Autowired
    public EmailService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送邮件服务
     * @param to 收件人邮箱
     * @param subject 标题
     * @param htmlContent html内容
     */
    public void sendEmail(String to, String subject, String htmlContent) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        byte[] utf8Bytes = submitter.getBytes(StandardCharsets.UTF_8);
        // 使用Base64编码字节数组
        byte[] encodedBytes = Base64.getEncoder().encode(utf8Bytes);
        // 将Base64编码后的字节数组转换为字符串
        String base64Encoded = new String(encodedBytes, StandardCharsets.UTF_8);

        helper.setFrom("'=?utf-8?B?"+base64Encoded+"?=' <"+email+">");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent,true);
        javaMailSender.send(message);
    }

}
